module mdiv(en, clk, rst, zn, clkn, clkout);
parameter NUM = 7;
input en, clk, rst;
input [NUM: 0] zn;
output clkn;
output clkout;
wire en, clk, rst;
wire [NUM: 0] zn;
reg clkn;
wire clkout;
reg clkn1;

reg [NUM: 0] cnt;
reg clk_neg;

assign clkout = zn[0] ? (en ? clkn & clk_neg : clkn) : (en ? clkn : clkn | clkn1);

always @(posedge clk or negedge rst)
	begin
		if (rst)
			begin
				cnt <= {NUM{1'b0}};
				clkn <= 1'b0;
			end
		else
			begin
				if (en && cnt == zn + 1 || !en && cnt == zn)
					begin
						cnt <= {NUM{1'b0}};
						clkn <= ~clkn;
					end
				else if (cnt == zn >> 1)
					begin
						cnt <= cnt + 1'b1;
						clkn <= ~clkn;
					end
				else
					begin
						cnt <= cnt + 1;
						clkn <= clkn;
					end
			end
	end

always@(negedge clk or posedge rst)
	begin
		if (rst)
			clk_neg <= 1'b0;
		else
			clk_neg <= clkn;
	end

always@(negedge clk or posedge rst)
	begin
		if (rst)
			clkn1 <= 1'b0;
		else if (en && cnt == zn + 1 || en && cnt == zn)
			clkn1 <= ~clkn1;
		else if (cnt == zn >> 1)
			clkn1 <= ~clkn1;
		else
			clkn1 <= clkn1;
	end
endmodule



module acct(clk, rst, ckn, enout);
input clk, rst, ckn;
output enout;

wire clk, rst, ckn;
reg enout;

wire ckn_go;
reg ckn_d;
reg [4: 0] cnt;

//采样器
assign ckn_go = ~ckn & ckn_d;
always@(posedge clk or posedge rst)
	begin
		if (rst)
			ckn_d <= 1'b0;
		else
			ckn_d <= ckn;
	end

//计数器
always@(posedge clk or posedge rst)
	begin
		if (rst)
			begin
				cnt <= 5'h00;
			end
		else if (cnt == 10)
			begin
				cnt <= 5'h00;
			end
		else
			cnt <= ckn_go ? cnt + 1 : cnt;
	end

//混频器
always@(posedge clk or posedge rst)
	begin
		if (rst)
			enout <= 1'b0;
		else
			case (cnt)
				5'd0, 5'd1, 5'd2, 5'd4, 5'd5, 5'd7, 5'd8:
					enout <= 1'b1;
				default:
					enout <= 1'b0;
			endcase
	end
endmodule


module fendiv(clk,rst,clkout);
input clk,rst;
output clkout;

wire clk,rst,clkout;

wire enout,clkn;

acct u_acct(
    .clk ( clk ),
    .rst ( rst ),
    .ckn ( ckn ),
    .enout ( enout )
);

mdiv u_mdiv(
    .en   ( enout   ),
    .clk  ( clk  ),
    .rst  ( rst  ),
    .zn   ( 'd7   ),
    .clkn ( clkn ),
    .clkout ( clkout )
);


endmodule
